package org.afraid.freedns.config;

import javax.servlet.http.HttpServletRequest;

import org.afraid.freedns.exception.APIException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import lombok.extern.slf4j.Slf4j;

/**
 * 控制层全局异常拦截，这里只拦截部分异常
 * 
 * @author jianggq
 * @date 2018年7月24日下午7:37:26
 */
@RestControllerAdvice({ "org.afraid.freedns.controller" })
@Slf4j
public class BasicExceptionHandler {

	/**
	 * 网站调用异常处理
	 * 
	 * @param e
	 * @param request
	 * @return
	 */
	@ExceptionHandler({ APIException.class })
	public ModelAndView apiException(APIException e, HttpServletRequest request) {
		log.error(e.getMessage(), e);
		return new ModelAndView("ftl/login", "errorMsg", e.getMessage());
	}

	/**
	 * valid 异常拦截处理，注：如果controller方法上加了BindingResult，那么这里不会拦截到
	 * 
	 * @param e
	 * @return
	 */
	@ExceptionHandler({ MethodArgumentNotValidException.class })
	public ModelAndView handleException(MethodArgumentNotValidException e) {
		log.error(e.getMessage(), e);

		BindingResult result = e.getBindingResult();
		return new ModelAndView("ftl/login", "errorMsg", result.getFieldError().getDefaultMessage());
	}

	/**
	 * 全局处理
	 * 
	 * @param e
	 * @param request
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	public ModelAndView exception(Exception e, HttpServletRequest request) {
		log.error(e.getMessage(), e);
		return new ModelAndView("ftl/login", "errorMsg", "系统异常 " + e.getMessage());
	}
}